<?php

namespace app\common\model\mall;

use app\common\model\Category;
use app\common\model\Collect;
use app\common\model\Store;
use think\Exception;
use think\Log;
use think\Model;
use traits\model\SoftDelete;

class Goods extends Model
{
    use SoftDelete;

    protected $name = 'goods';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'category_text',
        'image_url',
        'details_images_url'
    ];

    public function getCategoryTextAttr($value,$data)
    {
        $value = $value ? $value : (isset($data['category_id']) && $data['category_id'] ? $data['category_id'] : '');
        return Category::where('id',$value)->value('name');
    }

    public function getImageUrlAttr($value,$data)
    {
        $value = $value ? $value : (isset($data['image']) && $data['image'] ? $data['image'] : '');
        return $value ? cdnurl($value,true) :'';
    }

    public function getDetailsImagesUrlAttr($value,$data)
    {
        $value = $value ? $value : (isset($data['details_images']) && $data['details_images'] ? $data['details_images'] : '');
        $res = [];
        if($value){
            $tempArr = explode(',',$value);
            foreach ($tempArr as $v){
              if($v){
                  $res[] = cdnurl($v,true);
              }
            }
        }
        return $res;
    }

    public function store()
    {
        return $this->belongsTo(Store::class)->setEagerlyType(0);
    }

    public function sku()
    {
        return $this->hasMany(GoodsSku::class)->field('id,model,price,stock,sales,goods_id');
    }

    public function storecategory()
    {  //关联表；用于商家查找商品分类
        return $this->belongsToMany(Category::class,StoreGoodsCategory::class);
    }

    public function coupon()
    {   //关联表；用于商家查找优惠券
        return $this->belongsToMany(Coupon::class,StoreGoodsCoupon::class);
    }

    /**
     * 获取所有针对商家的收藏。
     */
    public function collect()
    {
        return $this->morphMany('Collect', 'type');
    }

    /**
     * 设置错误信息
     * @param $msg
     */
    public function setError($msg)
    {
        $this->error = $msg;
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * 商品列表
     * @param array $where
     * @param int $limit            数量
     * @param int $page             页码
     * @param bool $pageStatus       是否分页   false：不分页   true  分页
     * @param array $extend       补充参数，如 lng经度、lat 纬度用于计算距离distance
     * @return void
     */
    public function list($where= [], $limit = 10, $page = null, $pageStatus = false,$extend = []){
        try {
            $limit = $limit ? $limit : 10;
            $page = $page ? $page : 1;
            $tempWhere = [
                'state' => ['=','20'],    //  上架
            ];
            $field = 'id,status,name,category_id,coupon_switch,image,price,market_price,total_sales';
            $where = array_merge($tempWhere,$where);
            $sql = self::where($where)
                ->order('total_sales desc')
                ->field($field);
            if($pageStatus){
                $list = $sql->paginate($limit,true,['page'=>$page])->each(function ($item){
                    //优惠券
                    $tempCoupon = [];
                    if($item->coupon){
                        foreach ($item->coupon as $k=>$v){
                            if($v->endtime > time()){
                                $tempCoupon[] = ['id' => $v->id,'title'=> $v->getData('title'),'endtime' => $v->endtime,'quantity'=>$v->quantity];
                            }
                        }
                    }
                    unset($item->coupon);
                    $item->coupon = $tempCoupon;
                    return $item;
                });
            }else{
                $list = $sql->select();
                if($list ){
                    foreach ($list as $k=>&$v){
                        //优惠券
                        $tempCoupon = [];
                        if($v->coupon){
                            foreach ($v->coupon as $kk=>$vv){
                                if($vv->endtime > time()){
                                    $tempCoupon[] = ['id' => $vv->id,'title'=> $vv->getData('title'),'endtime' => $vv->endtime];
                                }
                            }
                        }
                        $v->coupon = $tempCoupon;
                    }
                }
            }
            return $list;
        }catch (Exception $e){
            Log::write('商品列表，SQL 语句：'.(new self())->getLastSql(),'log',true);
            $this->setError($e->getMessage());
            Log::write('商品列表，错误信息：'.$e->getMessage(),'error',true);
            return false;
        }
    }

    /**
     * 店铺详情
     * @param $store_id
     * @return void
     */
    public function details($goods_id,$user_id = null){
        try {
            $goods = self::get($goods_id);
            if(empty($goods)){
                $this->setError(__('No results were found'));
                return false;
            }
            if($goods->state !== '20'){
                $this->setError(__('商品已下架'));
                return false;
            }
            $data = [
                'id' => $goods->id,
                'status' => $goods->status,
                'name' => $goods->getData('name'),
                'image' => $goods->image_url,
                'price' => $goods->price,
                'market_price' => $goods->market_price,
                'total_sales' => $goods->total_sales,
                'freight' => $goods->freight,
                'sku' => $goods->sku,
                'details_text' => $goods->details_text,
                'details_images_url' => $goods->details_images_url,
                'coupon' => [],
                'store' => $goods->store->visible(['id','shop_name','logo_image','telephone','store_location','lng','lat','address']),
                'collect' => (bool)false,
                //'distance' => 0,//距离
                'store_id' => $goods->store_id,  //方便购物车使用
                'state' => $goods->state,  //方便购物车使用
            ];
            //优惠券
            if($goods->coupon){
                foreach ($goods->coupon as $k=>$v){
                    if($v->endtime >time()){
                        $temp = ['id' => $v->id,'title'=> $v->getData('title'),'endtime' => $v->endtime,'quantity' => $v->quantity];
                        $data['coupon'][] = $temp;
                    }
                }
            }
            //array_unique  移除数组中重复的值
            $data['coupon'] = array_unique($data['coupon'], SORT_REGULAR);
            //二维数组，根据某字段排序
            array_multisort(array_column($data['coupon'],'endtime'), SORT_ASC, SORT_NUMERIC,$data['coupon']);
            //收藏
            if($user_id){
                $data['collect'] = (bool)Collect::where(['user_id'=>['=',$user_id],'type'=>['=','20'],'data_id'=>['=',$goods_id]])->find();
            }
            return $data;
        } catch (Exception $e) {
            $this->setError($e->getMessage());
            return false;
        }
    }


}